package com.luo.demo.oidc.third.service;

import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义UserDetailsService实现
 *
 * @author luohq
 * @date 2022-03-05 11:40
 */
@Service
public class MyUserDetailsService implements UserDetailsService {
    @Resource
    private PasswordEncoder passwordEncoder;
    public Map<String, String> user2PasswordMap = new HashMap<>(1);
    public Map<String, String[]> user2AuthoritiesMap = new HashMap<>(1);

    @PostConstruct
    private void init() {
        this.user2PasswordMap.put("luo", this.passwordEncoder.encode("123456"));
        this.user2AuthoritiesMap.put("luo", new String[]{"temp"});
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (!this.user2PasswordMap.containsKey(username)) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        return User.builder()
                .username(username)
                .password(this.user2PasswordMap.get(username))
                .authorities(this.user2AuthoritiesMap.get(username))
                .build();
    }

}
